package com.bb.spring.email;

import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;

public class TemplateEmailService
{
	private JavaMailSender sender;
	private FreeMarkerConfigurer freeMarkerConfigurer = null;// FreeMarker的技术类

	public void setFreeMarkerConfigurer(
			FreeMarkerConfigurer freeMarkerConfigurer)
	{
		this.freeMarkerConfigurer = freeMarkerConfigurer;
	}

	public void setSender(JavaMailSender sender)
	{
		this.sender = sender;
	}

	// 通过模板构造邮件内容，参数username将替换模板文件中的${username}标签。
	private String getMailText(String username)
	{
		String htmlText = "";
		try
		{
			// 通过指定模板名获取FreeMarker模板实例
			Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate("registerUser.ftl");
			// FreeMarker通过Map传递动态数据
			Map map = new HashMap();
			map.put("username", username); // 注意动态数据的key和模板标签中指定的属性相匹配
			// 解析模板并替换动态数据，最终username将替换模板文件中的${username}标签。
			htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return htmlText;
	}

	// 发送模板邮件
	public void sendTemplateMail(String username) throws MessagingException
	{
		MimeMessage msg = sender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, false, "utf-8");// 由于是html邮件，不是mulitpart类型
		helper.setFrom("luanmad@163.com");
		helper.setTo("reg_2009_ok@163.com");
		helper.setSubject("注册成功-模板邮件");
		String htmlText = getMailText(username);// 使用模板生成html邮件内容
		helper.setText(htmlText, true);

		sender.send(msg);
		System.out.println("成功发送模板邮件");
	}

	public static void main(String[] args) throws MessagingException
	{
		// TODO Auto-generated method stub
		ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
		TemplateEmailService ms = (TemplateEmailService) ctx.getBean("templateEmail");

		// 发送模板邮件
		ms.sendTemplateMail("zoomhoo!");
	}// end method
}